var common = require('../../utils/common.js');
const app = getApp()
let newTime1 = new Date().getTime();

Page({
  data: {
    noReg: false,
    inAudit: false,
    auditPass: false,
    auditNoPass: false,
    activated: false,
    actEndTime: '2020/03/30 13:36:00',
    countDownList: [],
    inputTxt: '输入小店名称',
    logined: false,
    storeName: '',
    shopInfo: [],
    userInfo:[],
     items: [],
    isFromSearch: true,   // 用于判断searchSongList数组是不是空数组，默认true，空的数组  
    searchPageNum: 1,
    searchLoading: true,
    loading: false,
    itemIsShow: false,
    page: 1,
    checked: [],
    freeChecked: [],
    editMode: false,
    checkedSkuid:[],
    freeCheckedSkuid:[],
    thisChecked: false,
    noAll: true,
    showEditName: false,
    newName:'',
    swich: false,
    freeitems:[],
    freePage:1,
    statusBarHeight: app.globalData.statusBarHeight,
    regboxShow: false,
    telephone: '',
    telPass: false,
    weixin: 'jdxms212',
    urlpath: '',
    tabNav: [
      {
        name: '小店优选',
        path: '/app/v2/shop/list'
      },
      {
        name: '京东优选',
        path: '/app/v2/shop/systemChose'
      }
    ],
    currentTab:0,
    systemLoading: true,
    itemsloading: true,
    systemitems:[],
    navTab: 0,
    windowHeight: app.globalData.windowHeight,
    screenHeight: app.globalData.screenHeight,
    pixelRatio: app.globalData.pixelRatio,
    windowWidth: app.globalData.windowWidth,
    noAll: true,
    tipfirst2: true,
    syspage: 1,
    shareItem:[],
    showShare: false,
    imgSrc: '',
    showshareBox: false,
    shareItems2: [],
    thisfreeTxt: '',
    imgSrcSmall:'',
    imgSrc:'',
    shareTxt: '',
    shareTitle: '',
    shopfreeloaded: false,
    shopitemloaded: false,
    systemitemsloaded: false,
    mystoretabtop: '',
    fixed: false
  },
  onLoad: function (options) {
    if (app.globalData.sessionId !== undefined) {
      this.setData({
        logined: true
      })
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      this.getStoreInfo()
      this.getUserInfo()
      let promise = new Promise((resolve, reject) => {
        let timer = setInterval(() => {
          // console.log(app.globalData.sessionId,app.globalData.userId)
          if (that.data.shopInfo !== [] && that.data.userInfo !== []) {
            clearInterval(timer);
            resolve(that.data);
            wx.hideLoading()
          } else {
            //todo 信息构建中
          }
        }, 250);
      });
    }else{
      this.setData({
        logined: false
      })
      // this.loginTip()
    }
    this.countDown();
    const that = this
    wx.getStorage({
      key: 'tipfirst2',
      success (res) {
        console.log(res.data)
        that.setData({
          tipfirst2: res.data
        })
        console.log(that.data.tipfirst2)
      }
    })
  },
  onShow(){
    var that = this;
    let query = wx.createSelectorQuery()
    query.select('.tabNav').boundingClientRect( (rect) => {
      console.log(rect)
      this.setData({
        mystoretabtop: rect.top - rect.height
      })
      app.globalData.mystoretabtop = rect.top - rect.height
    }).exec()
    this.loginModal = this.selectComponent("#loginModal");
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2,
      })
      if (app.globalData.userInfo !== null && app.globalData.userInfo.hasShop !== undefined) {
        this.getTabBar().setData({
          hasShop: app.globalData.userInfo.hasShop,
        })
      } else {
        const that = this
        common.post({
          url: '/app/user/getInfo', data: { sessionId: this.data.sessionId }
        })
          .then((res) => {
            console.log(res.data)
            app.globalData.userInfo = res.data.data
            if (res.data.data.hasShop) {
              this.getTabBar().setData({
                hasShop: true,
              })
            } else {
              this.getTabBar().setData({
                hasShop: false,
              })
            }
          }).catch((res) => {
            console.log(res)
          })
      }
    }
    if (app.globalData.sessionId !== undefined) {
      this.setData({
        logined: true
      })
      this.getStoreInfo()
      this.getUserInfo()
     } else {
      this.setData({
        logined: false
      })
      // this.loginTip()
    }
    this.countDown();
  },
  onShareAppMessage() {
    var path= '/pages/shareShop/shareShop?userId=' + app.globalData.userInfo.userId
    var title = this.data.shopInfo.ownerName + '的小铺砸锅卖铁打折了，快来看看吧'
    var imageUrl = this.data.imgSrcSmall
    return {
      title: title,
      path: path,
      imageUrl: imageUrl
    }
  },
  timeFormat(param) {//小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  countDown() {//倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = this.data.actEndTime;
    let countDownArr = [];

    // 对结束时间进行处理渲染到页面
    // let endTime = new Date(endTimeList).getTime();
    let endTime = newTime1 + 86400000;
    // console.log(endTime, newTime)
    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      // let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 48) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      obj = {
        // day: this.timeFormat(day),
        hou: this.timeFormat(hou),
        min: this.timeFormat(min),
        sec: this.timeFormat(sec)
      }
      setTimeout(this.countDown, 1000);
    } else {//活动已结束，全部设置为'00'
      obj = {
        // day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      }
    }
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({ 
      countDownList: obj
    })
    // console.log(this.data.countDownList)
  },
  apply(){

  },
  loginTip() {
    console.log('登录')
    const that = this
    // wx.showModal({
    //   title: '提示',
    //   content: '你需要登录，才能访问我的小店',
    //   success(res) {
    //     if (res.confirm) {
    //       console.log('用户点击确定')
    //       wx.showLoading({
    //         title: '登录中...',
    //       })
    //       that.runLogin()
    //     } else if (res.cancel) {
    //       console.log('用户点击取消')
    //     }
    //   }
    // })
    this.loginModal.showPopup();
  },
  runLogin() {
    let res = app.login(app.globalData.thisshareTicket)
    this.waitLogin()
  },
  waitLogin() {
    const that = this
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (app.globalData.sessionId && app.globalData.userId) {
          clearInterval(timer);
          resolve(app.globalData);
          that.setData({
            logined: true,
            userInfo: app.globalData.userInfo
          })
          console.log(that.data.logined)
          wx.hideLoading()
          that.getStoreInfo()
          that.getUserInfo()
        } else {
          //todo 信息构建中
        }
      }, 250);
    });
    
  },
  getStoreInfo(){
    const that = this
    common.post({
      url: '/app/v2/shop/shopInfo', data: { userId: app.globalData.userId,sessionId: app.globalData.sessionId } })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0){
          switch (res.data.data.status) {
            case 0:
              that.setData({
                inAudit: true
              })
              break;
            case 1:
              that.setData({
                auditPass: true,
                shopInfo: res.data.data
              })
              break;
            case 2:
              that.setData({
                activated: true,
                shopInfo: res.data.data,
                swich:res.data.data.has99Banner
              })
              that.setData({
                urlpath: '/app/v2/shop/list'
              })
              that.getFreeitems()
              that.getShopItem()
              that.getsystemItem()
              let promise = new Promise((resolve, reject) => {
                let timer = setInterval(() => {
                  // console.log(app.globalData.sessionId,app.globalData.userId)
                  // console.log(that.data.systemitems)
                  if (that.data.shopfreeloaded && that.data.shopitemloaded && that.data.systemitemsloaded) {
                    clearInterval(timer);
                    resolve(app.globalData);
                    console.log('获取数据完成')
                    that.setData({
                      showShare: true
                    })
                  } else {
                    //todo 信息构建中
                  }
                }, 250);
              });
              break;
          }
        } else if(res.data.code == "-4"){
          that.setData({
            inAudit: true
          })
        } else if (res.data.code == "-1"){
          that.setData({
            noReg: true
          })
        } else if (res.data.code == "-3") {
          that.setData({
            noReg: true
          })
        }else if (res.data.code == "-2") {
          that.setData({
            noReg: true
          })
        } else if (res.data.code == "-9998"){
          // that.loginTip()
        }
        
      }).catch((res) => {
        console.log(res)
      })
  },
  getUserInfo(){
    const that = this
    common.post({
      url: '/app/user/getInfo', data: { sessionId: app.globalData.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          that.setData({
            userInfo: res.data.data
          })
        } else if (res.data.code == "-9998") {
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  inputWacth: function (e) {
    console.log(e);
    this.setData({
      storeName: e.detail.value
    });
  },
  apply(){
    const that = this
    if (this.data.storeName == ''){
      wx.showToast({
        title: '店铺名称不能为空',
        icon: 'none',
        duration: 2000
      })
    }else{
      common.post({
        url: '/app/v2/shop/apply', data: { shopName: this.data.storeName, sessionId: app.globalData.sessionId }
      })
        .then((res) => {
          console.log(res.data)
          if (res.data.code == 0){
            that.setData({
              noReg: false,
              inAudit: true
            })
            wx.showModal({
              title: '提示',
              content: '开启消息提示，店铺审核通过后，将及时通知您',
              confirmText: '开启',
              confirmColor: '#2365b7',
              success(res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                  that.sq()
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }else{
            console.log(res)
          }
        }).catch((res) => {
          console.log(res)
        })
    }
    
  },
  again(){
    this.setData({
      noReg: true,
      auditNoPass: false
    })
  },
  wxhelp(){
    const that = this
    wx.showModal({
      title: '提示',
      content: '您的专属辅导微信号:\r\n' + this.data.weixin + '\r\n关于省钱赚钱的问题,请复制微信号去微信添加好友咨询\r\n添加时请备注:京多多会员',
      confirmText: '复制',
      confirmColor: '#2365b7',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.setClipboardData({
            data: that.data.weixin,
            success(res) {
              wx.getClipboardData({
                success(res) {
                  console.log(res.data) // data
                }
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  buybtn(e) {
    console.log(e)
    // app.globalData.item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/pages/itemdetailNew/itemdetailNew?sku=' + e.currentTarget.dataset.item.skuId
    })
  },
  buybtn2(e) {
    console.log(e)
    // app.globalData.item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/pages/freeItemdetail/freeItemdetail?sku=' + e.currentTarget.dataset.item.skuId
    })
  },
  auto(){
    const that = this
    common.post({
      url: '/app/v2/shop/active', data: { sessionId: app.globalData.sessionId, shopName: this.data.shopInfo.shopName || this.data.storeName, isAutoChoose: true }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            activated: true,
            auditPass: false
          })
          that.getShopItem()
        } else if (res.data.code == "-9998") {
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  auto2() {
    const that = this
    common.post({
      url: '/app/v2/shop/updateMyShop', data: { sessionId: app.globalData.sessionId, shopName: this.data.shopInfo.shopName, isAutoChoose: true }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000
          })
          that.getShopItem()
          that.getStoreInfo()
        } else if (res.data.code == "-9998") {
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  manual(){
    const that = this
    common.post({
      url: '/app/v2/shop/active', data: { sessionId: app.globalData.sessionId, shopName: this.data.shopInfo.shopName, isAutoChoose: false }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            activated: true,
            auditPass: false
          })
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/itemlist/itemlist',
              success: function (res) {
                console.log('toIndex')
              },
              fail: function (res) {
                console.log(res)
              }
            })
          }, 2000);
          
        } else if (res.data.code == "-9998") {
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  manual2() {
    const that = this
    common.post({
      url: '/app/v2/shop/updateMyShop', data: { sessionId: app.globalData.sessionId, shopName: this.data.shopInfo.shopName, isAutoChoose: false }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000
          })
          that.getShopItem()
          that.getStoreInfo()
        } else if (res.data.code == "-9998") {
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  getShopItem() {
    this.setData({
      loading: true
    })
    const that = this
    common.post({
      url: '/app/v2/shop/list', data: { sessionId: app.globalData.sessionId, userId: app.globalData.userId, pageNo:1 }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data.total)
          that.setData({
            items: res.data.data,
            shopitemloaded: true
          })
          if(res.data.total < 11){
            that.setData({
              itemsloading: false
            })
          }
          
          // wx.hideLoading()
        } else if (res.data.code == "-9998") {
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  getShopItemPage() {
    const that = this;
    var page = that.data.page + 1;
    common.post({ url: '/app/v2/shop/list', data: { sessionId: app.globalData.sessionId, userId: app.globalData.userId, pageNo: page } })
      .then((res) => {
        var data = that.data.items;
        console.log(res.data)
        if (that.data.page * 10 < res.data.total) {
          that.setData({
            page: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
            console.log(data)
            that.setData({
              items: data,
            })
          }
        } else {
          console.log('没有了')
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
          that.setData({
            itemsloading: false
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  getsystemItem() {
    this.setData({
      loading: true
    })
    const that = this
    common.post({
      url: '/app/v2/shop/systemChose', data: { sessionId: app.globalData.sessionId, userId: app.globalData.userId, pageNo:1 }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data.total)
          that.setData({
            systemitems: res.data.data,
            systemitemsloaded: true
          })
          if(res.data.total < 11){
            that.setData({
              systemLoading: false
            })
          }
          // wx.hideLoading()
        } else if (res.data.code == "-9998") {
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  getsystemItemPage() {
    const that = this;
    var page = that.data.syspage + 1;
    common.post({ url: '/app/v2/shop/systemChose', data: { sessionId: app.globalData.sessionId, userId: app.globalData.userId, pageNo: page } })
      .then((res) => {
        var data = that.data.systemitems;
        console.log(res.data)
        if (that.data.syspage * 10 < res.data.total) {
          that.setData({
            syspage: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
            console.log(data)
            that.setData({
              systemitems: data,
            })
          }
        } else {
          console.log('没有了')
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
          that.setData({
            systemLoading: false
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  onReachBottom() {
    if(this.data.navTab == 0){
      this.getShopItemPage()
    }else{
      this.getsystemItemPage()
    }
  },
  checkboxChange: function (e) {
    console.log(e.detail.value)
    console.log(e)
    this.setData({
      checkedSkuid: e.detail.value
    })
    console.log(this.data.checkedSkuid)
  },
  getCheckidx(e){
    console.log(e)
    const that = this
    console.log(e.currentTarget.dataset.idx)
    var idx = e.currentTarget.dataset.idx
    console.log(this.data.checked[idx])
    if (this.data.checked[idx]){
      this.data.checked[idx] = false
      this.setData({
        checked: that.data.checked
      })
    }else{
      this.data.checked[idx] = true
      this.setData({
        checked: that.data.checked
      })
    }
    
    console.log(that.data.checked)
    
  },
  getFreeCheckidx(e){
    console.log(e)
    const that = this
    console.log(e.currentTarget.dataset.idx)
    var idx = e.currentTarget.dataset.idx
    console.log(this.data.freeChecked[idx])
    if (this.data.freeChecked[idx]){
      this.data.freeChecked[idx] = false
      this.setData({
        freeChecked: that.data.freeChecked
      })
    }else{
      this.data.freeChecked[idx] = true
      this.setData({
        freeChecked: that.data.freeChecked
      })
    }
    
    console.log(that.data.freeChecked)
  },
  edit(){
    this.setData({
      editMode: true
    })
  },
  deleteItem(){
    const that = this;
    var skuIdlist = [...this.data.checkedSkuid,...this.data.freeCheckedSkuid];
    console.log(skuIdlist)
    if (this.data.checkedSkuid.length > 0){
      common.post({ url: '/app/v2/shop/delProduct', data: { sessionId: app.globalData.sessionId, skuId: skuIdlist } })
        .then((res) => {
          console.log(res.data)
          if (res.data.code == 0) {
            wx.showLoading({
              title: '正在删除中',
            })
            that.setData({
              checkedSkuid: [],
              thisChecked: false
            })
            if(that.data.currentTab == 0){
              console.log('删除商品')
              that.getShopItem()
              that.getFreeitems()
            }
          } else {
            console.log(res.data)
          }
        }).catch((res) => {
          console.log(res)

        })
    }else{
      wx.showToast({
        title: '还没有选择商品',
        icon: 'none',
        duration: 2000
      })
    }
  },
  allSelect(){
    console.log('all')
    this.setData({
      thisChecked: true,
      noAll: false
    })
    console.log(this.data.items)
    for (let i = 0; i < this.data.items.length; i++) {
      this.data.checked[i] = true
      this.data.checkedSkuid[i] = this.data.items[i].skuId
      this.setData({
        checkedSkuid: this.data.checkedSkuid
      })
      this.setData({
        checked: this.data.checked
      })
      console.log(this.data.checked)
      console.log(this.data.checkedSkuid)
    }
    console.log(this.data.freeitems)
    for (let i = 0; i < this.data.freeitems.length; i++) {
      this.data.freeChecked[i] = true
      this.data.freeCheckedSkuid[i] = this.data.freeitems[i].skuId
      this.setData({
        freeCheckedSkuid: this.data.freeCheckedSkuid
      })
      this.setData({
        freeChecked: this.data.freeChecked
      })
      console.log(this.data.freeChecked)
      console.log(this.data.freeCheckedSkuid)
    }
  },
  cancelSelect() {
    console.log('cancelall')
    this.setData({
      thisChecked: false,
      noAll: true,
      checkedSkuid: [],
      freeCheckedSkuid: []
    })
    console.log(this.data.items)
    for (let i = 0; i < this.data.items.length; i++) {
      this.data.checked[i] = false
      this.setData({
        checked: this.data.checked
      })
      console.log(this.data.checked)
      console.log(this.data.checkedSkuid)
    }
    for (let i = 0; i < this.data.freeitems.length; i++) {
      this.data.freeChecked[i] = false
      this.setData({
        freeChecked: this.data.freeChecked
      })
      console.log(this.data.freeChecked)
      console.log(this.data.freeCheckedSkuid)
    }
  },
  editName(){
    this.setData({
      showEditName: true
    })
  },
  nameWacth(e){
    console.log(e);
    this.setData({
      newName: e.detail.value
    });
  },
  modifyName(){
    const that = this
    common.post({ url: '/app/v2/shop/updateMyShop', data: { sessionId: app.globalData.sessionId, shopName: this.data.newName } })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            showEditName: false
          })
        } else {
          console.log(res.data)
        }
      }).catch((res) => {
        console.log(res)

      })
  },
  cancelEdit(){
    this.setData({
      showEditName: false,
      editMode: false
    })
  },
  sq() {
    wx.requestSubscribeMessage({
      tmplIds: ['4sS4XSaGBx1JW8YMoiOXBVXYyaoh0r4Gfukac1P4e5w', '3xGc_5HQYMaEhojk2MK6SEevITaQnqRfDCF8JPfHoYg'],
      success(res) {
        console.log(res)
      },
      fail(res) {
        console.log(res)
      }
    })
  },
  getPhoneNumber(e){
    console.log(e)
    const that = this
    if(!this.data.telPass){
      wx.checkSession({
        success(res) {
          console.log(res)
          common.post({ url: '/app/user/getWxPhoneNumber', data: { sessionId: app.globalData.sessionId, iv: e.detail.iv, encryptedData: e.detail.encryptedData  } })
            .then((res) => {
              console.log(res.data)
              if (res.data.code == 0) {
                that.setData({
                  telephone: res.data.data.phoneNumber,
                  telPass: true
                })
              } else {
                console.log(res.data)
              }
            }).catch((res) => {
              console.log(res)
  
            })
        },
        fail() {
          app.login() //重新登录
        }
      })
    }
    
  },
  regShop(){
    const that = this
    if(this.data.telephone == ''){
        wx.showToast({
          title: '请先验证手机号',
          icon: 'none',
          duration: 2000
        })
    }else if(this.data.storeName == ''){
      wx.showToast({
        title: '请填写小店名称',
        icon: 'none',
        duration: 2000
      })
    }else{
      common.post({
        url: '/app/v2/shop/apply', data: { shopName: this.data.storeName, sessionId: app.globalData.sessionId, telephone: this.data.telephone }
      })
        .then((res) => {
          console.log(res.data)
          if (res.data.code == 0) {
            that.sq()
            that.setData({
              noReg: false,
              inAudit: true,
              regboxShow: false
            })
           } else {
            console.log(res)
          }
        }).catch((res) => {
          console.log(res)
        })
    }
    
  },
  clickSwich(){
    const that = this
    common.post({ url: '/app/v2/shop/setHas99Banner', data: { sessionId: app.globalData.sessionId, has99Banner: !this.data.swich } })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          that.setData({
            showEditName: false,
            swich: !this.data.swich
          })
          that.getFreeitems()
        } else {
          console.log(res.data)
        }
      }).catch((res) => {
        console.log(res)

      })
  },
  getFreeitems() {
    console.log(1)
    const that = this
    common.post({ url: '/app/v2/shop/free99', data: { userId: app.globalData.userId, pageNo: 1,pageSize: 9 } })
      .then((res) => {
        console.log(res.data)
        // var data=[]
        //     console.log(res.data)
        //     var subdata = res.data.data
        //     for(let i=0; i<subdata.length; i+=3){
        //       data.push(subdata.slice(i,i+3))
        //     }
        //     console.log(data)
        //       that.setData({
        //         freeitems: data
        //       });
        // console.log(that.data.freeitems)
        that.setData({
          freeitems: res.data.data,
          shopfreeloaded: true,
        });
        console.log(that.data.freeitems)
      }).catch((res) => {
        console.log(res)
      })
      
  },
  getFreeitemsPage() {
    const that = this;
    var page = that.data.freePage + 1;
    common.post({ url: '/app/v2/shop/free99', data: { userId: app.globalData.userId, pageNo: page,pageSize: 9 } })
      .then((res) => {
        var data = [];
        console.log(res.data)
        if (that.data.page * 10 < res.data.total) {
          that.setData({
            freePage: page
          });
          var j = page + 1
          var postList = res.data.data;
          var rdata=[],subdata=[]
          for(let i=0; i<postList.length; i+=3){
            let tmp = postList[i];
            subdata.push(tmp)
            console.log(subdata)
            rdata.push(postList.slice(i,i+3))
          }
          var arr = [...that.data.freeitems,...rdata]
          that.setData({
            freeitems: arr,
          })
          console.log(that.data.freeitems)
        } else {
          console.log('没有了')
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  swChange(e) {
    console.log(e,e.detail.current,e.target.dataset.length)
    this.setData({
      currentTab: e.detail.current
    })
    if (e.detail.current == e.target.dataset.length - 1) {
      console.log('分页')
      this.getFreeitemsPage()
    }
  },
  toInitiateJl() {
    wx.navigateTo({
      url: '/pages/initiateJl/initiateJl',
      success: function (res) {
        console.log('toInitiateJl')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  editItem(){
    const that = this
    if(this.data.items.length > 0 || this.data.freeitems.length > 0){
      this.setData({
        editMode: true
      })
    }else{
      wx.getClipboardData({
        success(res) {
          console.log(res.data) // data
          wx.showToast({
            title: '店里还没有商品',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  },
  regbtn(){
    if(app.globalData.sessionId){
      this.setData({
        regboxShow: true
      })
    }else{
      this.loginTip()
    }
    
  },
  closeRegbox(){
    this.setData({
      regboxShow: false
    })
  },
  toAboutCompany(){
    wx.navigateTo({
      url: '/pages/help1/help1',
      success: function (res) {
        console.log('tohelp1')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  advisory(){
    wx.setClipboardData({
      data: this.data.weixin,
      success(res) {
        wx.getClipboardData({
          success(res) {
            console.log(res.data) // data
            wx.showToast({
              title: '复制成功',
              icon: 'success',
              duration: 2000
            })
          }
        })
      },
      fail(res){
        console.log(res)
      }
    })
  },
  toIndex(){
    
  },
  toSetting(){
    const that = this
    wx.navigateTo({
      url: '/pages/shopSetting/shopSetting',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function(data) {
          console.log(data)
        },
        someEvent: function(data) {
          console.log(data)
        }
      },
      success: function (res) {
        console.log('toShopSetting')
        res.eventChannel.emit('acceptDataFromOpenerPage', { shopInfo: that.data.shopInfo })
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  jlshare(e){
    console.log(e)
    const that = this
    wx.navigateTo({
      url: '/pages/createSolitaire/createSolitaire',
      events: {
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
      success: function (res) {
        console.log('toCreateSolitaire')
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: e.currentTarget.dataset.item })
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toFreeZone(){
    wx.navigateTo({
      url: '/pages/freeItem/freeItem?from=free',
      success: function (res) {
        console.log('toInitiateJl')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toitemZone(){
    wx.navigateTo({
      url: '/pages/freeItem/freeItem?from=item',
      success: function (res) {
        console.log('toInitiateJl')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  tabChange(e){
    console.log(e)
    var num = e.currentTarget.dataset.index
    this.setData({
      urlpath: e.currentTarget.dataset.path
    })
    this.setData({
      navTab: num
    })
    if(num == 0){
      if(this.data.items.length < 1){
        this.getShopItem()
      }
    }else if(num == 1){
      if(this.data.systemitems.length < 1){
        this.getsystemItem()
      }
    }
  },
  closeTip(){
    this.setData({
      showShare: false
    })
    wx.setStorage({
      key:"tipfirst2",
      data:false
    })
  },
  shareShop(){
    if(this.data.shopfreeloaded && this.data.shopitemloaded && this.data.systemitemsloaded){
      wx.showLoading({
        title: '生成中...',
        mask: true
      })
      var freeitems = this.data.freeitems,
      systemItems = this.data.systemitems
      items = this.data.items,
      sub1 = [],sub2=[],sub3=[],shareItems=[],shareItems2=[]
      if(freeitems.length > 2){
        console.log('免单商品3个以上')
        sub1 = freeitems.slice(0,3);
        this.setData({
          thisfreeTxt: '0元购'
        })
        shareItems2 = sub1
        if(items.length > 2){
          console.log('小铺商品3个以上')
          sub2 = items.slice(0,3);
          shareItems = [...sub1,...sub2]
        }else{
          console.log('小铺商品不足3个')
          for(let i=0;i<items.length;i++){
            sub2.push(items[i])
          }
          var num = 3 - items.length
          for(let i=0;i<num;i++){
            sub3.push(systemItems[i])
          }
          shareItems = [...sub1,...sub2,...sub3]
        }
      }else{
        console.log('免单商品不足3个')
        this.setData({
          thisfreeTxt: '上新'
        })
        for(let i=0; i<freeitems.length; i++){
          sub1.push(freeitems[i]) 
        }
        var num = 6 - freeitems.length
        if(items.length > num){
          console.log('小铺商品加免单商品6个以上')
          sub2 = item.slice(0,num);
          shareItems = [...sub1,...sub2]
        }else{
          console.log('小铺商品加免单商品不足6个')
          console.log(systemItems)
          for(let i=0; i<items.length; i++){
            sub2.push(items[i]) 
          }
          for(let i=0; i<num; i++){
            sub3.push(systemItems[i])
          }
          shareItems = [...sub1,...sub2,...sub3]
        }
        if(items.length > 3){
          sub2 = items.slice(0,3);
          shareItems2 = sub2
        }else if(items.length > 0){
          var num = 3 - freeitems.length
          for(let i=0; i<items.length; i++){
            sub2.push(items[i]) 
          }
          for(let i=0; i<num; i++){
            sub3.push(systemItems[i])
          }
          shareItems2 = [...sub2,...sub3]
        }else{
          sub2 = systemItems.slice(0,3);
        }
      }
      console.log(shareItems)
      console.log(shareItems2)
      this.setData({
        shareItem: shareItems,
        shareItem2: shareItems2
      })
      console.log('选择画布')
      const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
      query.select('#canvas').fields({
        node: true,
        rect: true,
        size: true
      }, res => {
        const canvas = res.node;
        canvas.width = 828 * 1;//本地图像的width
        canvas.height = 1472 * 1;//本地图像的height
        console.log(canvas)
        const ctx = canvas.getContext('2d');
        this.render(canvas, ctx);
      }).exec()
    }else{
      wx.showModal({
        title: '提示',
        content: '数据还没有加载完成，请稍后...',
        showCancel: false,
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
    }
    
  },
  canvas1(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas1').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 500;//本地图像的width
      canvas.height = 400;//本地图像的height
      this.render2(canvas, ctx);
    }).exec()
  },
   // 生成分享图

   render(canvas, ctx) {
    const that = this
    this.drawIteminfo(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawShopInfo(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawshopkeeper(ctx,canvas).then(function(){
          console.log('第三步完成')
          that.drawDcode(ctx,canvas).then(function(){
            console.log('第四步完成')
            that.drawItem(ctx,canvas,0).then(function(){
              console.log('第五步完成')
              that.drawItem(ctx,canvas,1).then(function(){
                console.log('第六步完成')
                that.drawItem(ctx,canvas,2).then(function(){
                  console.log('第七步完成')
                  that.drawItem(ctx,canvas,3).then(function(){
                    console.log('第八步完成')
                    that.drawItem(ctx,canvas,4).then(function(){
                      console.log('第九步完成')
                      that.drawItem(ctx,canvas,5).then(function(){
                        console.log('第十步完成')
                        that.drawTag(ctx,canvas).then(function(){
                          console.log('第十一步完成')
                          that.drawCanvas(canvas)
                        })
                        
                      })
                    })
                  })
                })
              })
            })
          })
        })
      })
      // that.canvas1()
    })
  },
  render2(canvas, ctx){
    const that = this
    that.drawSmallpic(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawItemSmall(ctx,canvas,0).then(function(){
        console.log('第二步完成')
        that.drawItemSmall(ctx,canvas,1).then(function(){
          console.log('第三步完成')
          that.drawItemSmall(ctx,canvas,2).then(function(){
            console.log('第四步完成')
            that.drawCanvas2(canvas)
          })
        })
      })
    })
  },
  drawIteminfo(ctx,canvas){
    console.log('开始绘图')
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 828, 1472);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/shop_share@3x.jpg'
    })
  },
  drawShopInfo(ctx,canvas){
    const that = this
    let txt1 = this.data.shopInfo.shopName
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 72, x = 342, y = 60
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 142, 142);
        ctx.restore()
        console.log('绘制头像完成')
        ctx.strokeStyle = "#ffffff";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "44px PingFangSC-Semibold";
        }else{
          ctx.font = "bold 44px NotoSans-Bold";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(txt1, 414, 238);
        console.log('绘制文字完成')
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shopInfo.avatar
    })
  },
  drawTag(ctx,canvas){
    let txt2 = this.data.shopInfo.fansCount + '位粉丝'
    let x = 352,y = 276, r = 4, w = 126, h = 40
    return new Promise(function (resolve, reject) {
      ctx.beginPath()
      ctx.save()
      // ctx.beginPath()
      // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
      // 这里是使用 fill 还是 stroke都可以，二选一即可
      // ctx.fillStyle = 'transparent'
      ctx.fillStyle = 'transparent'
      // 左上角
      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
      // 右上角
      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
      // 左下角
      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
      ctx.fillStyle = 'rgba(255, 255, 255, 0.2)'
      ctx.fill()
      ctx.closePath()
      // 剪切
      ctx.clip()
      ctx.restore();
      if(app.globalData.isIphone){
        ctx.font = "22px PingFangSC-Semibold";
      }else{
        ctx.font = "bold 22px NotoSans-Bold";
      }
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillStyle = "#fff";
      ctx.fillText(txt2, 414, 296);
      ctx.closePath();
      resolve()
    })
  },
  // 绘制头像
  drawshopkeeper(ctx,canvas){
    const that = this
    let txt1 = this.data.shopInfo.ownerName + ' 邀请你进入他的小店',
        txt2 = '长按识别二维码进入小店'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 46, x = 42, y = 1318
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Medium";
        }else{
          ctx.font = "26px NotoSans-Medium";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 148, 1358);
        if(!app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Light";
        }else{
          ctx.font = "lighter 26px NotoSans";
        }
        ctx.fillText(txt2, 148, 1394);
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shopInfo.avatar
    })
  },
  // 绘制二维码
  drawDcode(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      var scene = 'userId=' + app.globalData.userInfo.userId
      common.post({
        url: '/wxa/qrcode/getUnlimitQrcode', 
        data: {
          scene: scene,
          // page: 'pages/shareShop/shareShop',
          page: 'pages/itemlist/itemlist',
          sessionId: app.globalData.sessionId,
          width: '236',
          auto_color: 'false',
          line_color: '{"r":"255","g":"85","b":"85"}',
          is_hyaline: 'false'
        }
      })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          let img = canvas.createImage();
          img.onload = (e) => {
            console.log('img loaded')
            ctx.beginPath()
            let r = 68, x = 652, y = 1296
            ctx.save()
            ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.clip()
            ctx.drawImage(img, x + 7, y + 7, 122, 122);
            ctx.restore()
            ctx.closePath();
            resolve()
          }
          img.onerror = (e) => {
            console.error('err:', e)
          }
          img.src = res.data.qrcodeLink
        }else{
          wx.hideLoading()
          that.loginTip()
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
    })
  },
  // 绘制商品图1
  drawItem(ctx,canvas,i){
    const that = this
    var row1size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }
        finalStr += name[i];
        if (length > 8) {
          break;
        }
      }
      return finalStr;
    }
    var findcoupons = function (coupons) {
      var val=0;
      if(coupons.length == 1){
          return val = coupons[0].discount
      }else {
          for(var i=0; i < coupons.length; ++i){
              if(val < coupons[i].discount){
                  val = coupons[i].discount
              }
          }
          return val
      }
    }
    var format = function(value){
      var html,_val;
      value =Number(value).toFixed(1);
      if(value==0){
          value=0;
          return html = "0";
      }else {
          value = Number(value).toFixed(1);
      }
      _val = value.split('.');
      return html = _val[0]+'.'+_val[1];
    }
    switch(i){
      case 0:
        var x = 48,y = 488, r = 8, w = 228, h = 228,
            circleX1 = 120, circleY = 784, circleR = 20,
            circleX2 = 204, 
            rectangleX = 120, rectangleY = 764, rectangleW = 84, rectangleH = 40,
            txt1X = 162, txt1Y = 740,
            txt2X = 162, txt2Y = 786,
            priceNewX = 159, priceNewY = 795,
            priceOldX = 165, priceOldY = 797
        break;
      case 1:
        var x = 300,y = 488, r = 8, w = 228, h = 228,
            circleX1 = 372, circleY = 784, circleR = 20,
            circleX2 = 456, 
            rectangleX = 372, rectangleY = 764, rectangleW = 84, rectangleH = 40,
            txt1X = 414, txt1Y = 740,
            txt2X = 414, txt2Y = 786,
            priceNewX = 413, priceNewY = 795,
            priceOldX = 417, priceOldY = 797
        break;
      case 2:
        var x = 552,y = 488, r = 8, w = 228, h = 228,
            circleX1 = 624, circleY = 784, circleR = 20,
            circleX2 = 708, 
            rectangleX = 624, rectangleY = 764, rectangleW = 84, rectangleH = 40,
            txt1X = 667, txt1Y = 740,
            txt2X = 667, txt2Y = 786,
            priceNewX = 664, priceNewY = 795,
            priceOldX = 670, priceOldY = 797
        break;
      case 3:
        var x = 48,y = 878, r = 8, w = 228, h = 228,
            circleX1 = 120, circleY = 1174, circleR = 20,
            circleX2 = 204, 
            rectangleX = 120, rectangleY = 1154, rectangleW = 84, rectangleH = 40,
            txt1X = 162, txt1Y = 1134,
            txt2X = 162, txt2Y = 1176,
            priceNewX = 159, priceNewY = 1185,
            priceOldX = 165, priceOldY = 1187
        break;
      case 4:
        var x = 300,y = 878, r = 8, w = 228, h = 228,
            circleX1 = 372, circleY = 1174, circleR = 20,
            circleX2 = 456, 
            rectangleX = 372, rectangleY = 1154, rectangleW = 84, rectangleH = 40,
            txt1X = 414, txt1Y = 1134,
            txt2X = 414, txt2Y = 1176,
            priceNewX = 413, priceNewY = 1185,
            priceOldX = 417, priceOldY = 1187
        break;
      case 5:
        var x = 552,y = 878, r = 8, w = 228, h = 228,
            circleX1 = 584, circleY = 1174, circleR = 20,
            circleX2 = 668, 
            rectangleX = 584, rectangleY = 1154, rectangleW = 84, rectangleH = 40,
            txt1X = 667, txt1Y = 1134,
            txt2X = 667, txt2Y = 1176,
            priceNewX = 664, priceNewY = 1185,
            priceOldX = 670, priceOldY = 1187
        break;
    }
    console.log(i)
    console.log(that.data.shareItem[i])
    var item = that.data.shareItem[i]
    var txt1 = row1size(item.title),
        txt2 = '限时免单'
    var priceNew = '',
        priceOld = '￥' + item.price
    var lineWidth = ctx.measureText(priceOld)
    if(item.coupons){
      priceNew = '￥' + format(item.price - findcoupons(item.coupons))
    }else{
      priceNew = '￥' + priceOld
    }
    
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        ctx.beginPath()
        console.log('img loaded')
        ctx.save()
        ctx.setFillStyle = 'transparent'
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        ctx.closePath()
        ctx.clip()
        ctx.drawImage(img, x, y, w, h);
        ctx.restore();
        ctx.beginPath()
        if(app.globalData.isIphone){
          ctx.font = "23px PingFangSC-Medium";
        }else{
          ctx.font = "23px NotoSans-Medium";
        }
        ctx.fillStyle = "#505050";
        ctx.textAlign = 'center';
        ctx.fillText(txt1, txt1X, txt1Y);
        console.log(item.is99)
        if(item.is99){
          ctx.arc(circleX1,circleY,circleR,0,2*Math.PI)
          ctx.fillStyle = "#FFE232"
          ctx.fill()
          ctx.arc(circleX2,circleY,circleR,0,2*Math.PI)
          ctx.fillStyle = "#FFE232"
          ctx.fill()
          ctx.fillRect(rectangleX,rectangleY,rectangleW,rectangleH)
          ctx.fillStyle = "#000";
          ctx.fillText(txt2, txt2X, txt2Y);
        }else{
          if(app.globalData.isIphone){
            ctx.font = "27px PingFangSC-Semibold";
          }else{
            ctx.font = "bold 27px NotoSans-Bold";
          }
          ctx.fillStyle = "#FF5555";
          ctx.textAlign = 'right';
          ctx.fillText(priceNew, priceNewX, priceNewY);
          if(app.globalData.isIphone){
            ctx.font = "23px PingFangSC-Semibold";
          }else{
            ctx.font = "bold 23px NotoSans-Bold";
          }
          ctx.fillStyle = "#BCBCBC";
          ctx.textAlign = 'left';
          ctx.fillText(priceOld, priceOldX, priceOldY);
          ctx.fillStyle = "#BCBCBC";
          ctx.fillRect(priceOldX, priceOldY - 4, lineWidth.width, 2)
        }
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = item.image
    })
  },
  // 生成图片
  drawCanvas(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 828,
        height: 1472,
        destWidth:828,
        destHeight:1472,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrc:res.tempFilePath,
          })
          that.canvas1()
          // wx.hideLoading()
        }
      })
    })
  },
  // 绘制分享小图
  drawSmallpic(ctx,canvas){
    const that = this
    let shopName = this.data.shopInfo.shopName,
        txt1 = '以上为今日' + this.data.thisfreeTxt + '的商品哦',
        txt2 = '快来看看吧！'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        ctx.fillStyle = '#FF5555'
        ctx.fillRect(0,0,500,400)
        ctx.font = "bold 24px PingFangSC-Semibold";
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(shopName, 128, 68);
        ctx.textAlign = 'center';
        ctx.font = "bold 32px PingFangSC-Semibold";
        ctx.fillStyle = '#FFF617'
        ctx.fillText(txt1, 250, 334);
        ctx.font = "bold 24px PingFangSC-Semibold";
        ctx.fillText(txt2, 250, 368);
        let r = 46, x = 9, y = 9
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shopInfo.avatar
    })
  },
  drawItemSmall(ctx,canvas,i){
    const that = this
    switch(i){
      case 0:
        var x = 16,y = 136, r = 4, w = 152, h = 152
        break;
      case 1:
        var x = 174,y = 136, r = 4, w = 152, h = 152
        break;
      case 2:
        var x = 332,y = 136, r = 4, w = 152, h = 152
        break;
    }
    console.log(i)
    console.log(that.data.shareItem[i])
    var item = that.data.shareItem[i]
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        ctx.beginPath()
        console.log('img loaded')
        ctx.save()
        ctx.setFillStyle = 'transparent'
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        ctx.closePath()
        ctx.clip()
        ctx.drawImage(img, x, y, w, h);
        ctx.restore();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = item.image
    })
  },
  drawCanvas2(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 500,
        height: 400,
        destWidth:500,
        destHeight:400,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrcSmall:res.tempFilePath,
            showshareBox: true,
            shareTxt: '小铺开张大吉，财源广进'
          })
          wx.hideLoading()
        }
      })
    })
  },
  saveSharePic(){
    wx.saveImageToPhotosAlbum({
      filePath: this.data.imgSrc,
      success: function (data) {
          wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
          })
      },
      fail: function (err) {
          console.log(err);
          if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权")
              wx.openSetting({
                  success(settingdata) {
                      console.log(settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                      } else {
                          console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                      }
                  }
              })
          } else {
              wx.showToast({
                  title: '保存失败',
                  icon: 'none'
              });
          }
      },
      complete(res) {
          console.log(res);
      }
    })
  },
  closeSharePic(){
    console.log('关闭')
    this.setData({
      showshareBox: false
    })
  },
  jlshare(e){
    console.log(e)
    const that = this
    wx.navigateTo({
      url: '/pages/createSolitaire/createSolitaire',
      events: {
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
      success: function (res) {
        console.log('toCreateSolitaire')
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: e.currentTarget.dataset.item })
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  buyedshare(e){
    this.setData({
      buyedItem: e.currentTarget.dataset.item
    })
    this.canvas5()
  },
  // 选择画布
  canvas5(){
    wx.showLoading({
      title: '分享图生成中',
      mask: true
    })
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 828;//本地图像的width
      canvas.height = 1472;//本地图像的height
      this.render5(canvas, ctx);
    }).exec()
  },
  canvas6(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas1').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 500;//本地图像的width
      canvas.height = 400;//本地图像的height
      this.render6(canvas, ctx);
    }).exec()
  },
 
  // 生成分享图

  render5(canvas, ctx) {
    const that = this
    this.drawIteminfo3(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawItemPic3(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawItemTag3(ctx,canvas).then(function(){
          console.log('第三步完成')
          that.drawAvatar3(ctx,canvas).then(function(){
            console.log('第四步完成')
            that.drawDcode3(ctx,canvas).then(function(){
              console.log('第五步完成')
              that.drawCashbackinfo3(ctx,canvas).then(function(){
                console.log('第六步完成')
                that.drawCanvas5(canvas)
                that.canvas6()
              })
            })
          })
        })
      })
    })
  },
  render6(canvas, ctx){
    const that = this
    that.drawSmallpic3(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawSmalltag3(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawCanvas6(canvas)
      })
    })
  },
  // 绘制分享小图
  drawSmallpic3(ctx,canvas){
    var findcoupons = function (coupons) {
      var val=0;
      if(coupons.length == 1){
          return val = coupons[0].discount
      }else {
          for(var i=0; i < coupons.length; ++i){
              if(val < coupons[i].discount){
                  val = coupons[i].discount
              }
          }
          return val
      }
    }
    var format = function(value){
      var html,_val;
      value =Number(value).toFixed(1);
      if(value==0){
          value=0;
          return html = "0";
      }else {
          value = Number(value).toFixed(1);
      }
      _val = value.split('.');
      return html = _val[0]+'.'+_val[1];
    }
    const that = this
    
    let item = this.data.buyedItem,
        txt1 = '抢券价 ￥',
        priceNew = '',
        txt2 = '京东价',
        priceOld = '¥' + item.price
    if(item.coupons){
      priceNew = format(item.price - findcoupons(item.coupons))
    }else{
      priceNew = priceOld
    }
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 500, 500);
        ctx.fillStyle = '#FF5555'
        ctx.fillRect(0,320,500,80)
        ctx.font = "bold 22px PingFangSC-Semibold";
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 16, 385);
        let txt1width = ctx.measureText(txt1).width + 16
        ctx.font = "bold 50px PingFangSC-Semibold";
        ctx.fillText(priceNew, txt1width, 385);
        let priceNewWidth = ctx.measureText(priceNew).width + txt1width + 20
        ctx.font = "bold 22px PingFangSC-Semibold";
        ctx.fillText(txt2, priceNewWidth, 385);
        let txt2width = ctx.measureText(txt2).width + priceNewWidth
        ctx.fillText(priceOld, txt2width, 385);
        let priceOldWidth = ctx.measureText(priceOld).width
        ctx.beginPath()
        ctx.strokeStyle = '#fff'
        ctx.moveTo(txt2width, 376)
        ctx.lineTo(txt2width + priceOldWidth, 376)
        ctx.stroke()
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = item.image
    })
  },
  // 绘制商品标签
  drawSmalltag3(ctx,canvas){
    const that = this
    let item = this.data.buyedItem
    var goodCommentsRate = '100'
    if(item.goodCommentsRate > 0){
      goodCommentsRate = item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 12, 12, 200, 36);
        ctx.font = "20px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 146, 38);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 46, 38);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制内容
  drawIteminfo3(ctx,canvas){
    console.log('开始绘图')
    var row1size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }

        finalStr += name[i];
        if (length > 18) {
          break;
        }
      }
      return finalStr;
    }
    var row2size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }
        if (length > 19) {
          finalStr += name[i];
        }
        if (length > 35) {
          break;
        }
      }
      return finalStr + '...';
    }
    var findcoupons = function (coupons) {
      var val=0;
      if(coupons.length == 1){
          return val = coupons[0].discount
      }else {
          for(var i=0; i < coupons.length; ++i){
              if(val < coupons[i].discount){
                  val = coupons[i].discount
              }
          }
          return val
      }
    }
    var format = function(value){
      var html,_val;
      value =Number(value).toFixed(1);
      if(value==0){
          value=0;
          return html = "0";
      }else {
          value = Number(value).toFixed(1);
      }
      _val = value.split('.');
      return html = _val[0]+'.'+_val[1];
    }
    let item = this.data.buyedItem,
        itemName = item.title,
        str1 = row1size(itemName),
        str2 = row2size(itemName),
        priceNew = '',
        priceOld = format(item.price),
        priceNewTxt = '抢券价',
        priceOldTxt = '京东价'
        // txt1 = solitaire.partnerCount + '人参与了群接龙567'
    if(item.coupons){
      priceNew = format(item.price - findcoupons(item.coupons))
    }else{
      priceNew = priceOld
    }
    const that = this;
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 828, 1472);
        ctx.font = "30px PingFangSC-Medium";
        ctx.fillStyle = "#363636";
        ctx.textAlign = 'center';
        ctx.fillText(str1, 414, 904);
        ctx.fillText(str2, 414, 946);
        ctx.font = "bold 26px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.fillText(priceNewTxt, 303, 998);
        ctx.font = "bold 44px PingFangSC-Semibold";
        ctx.fillText(priceNew, 303, 1058);
        ctx.font = "bold 26px PingFangSC-Semibold";
        ctx.fillStyle = "#505050";
        ctx.fillText(priceOldTxt, 530, 998);
        ctx.font = "bold 44px PingFangSC-Semibold";
        ctx.fillText(priceOld, 530, 1058);
        let lineWidth = ctx.measureText(priceOld).width
        console.log('线长度',lineWidth)
        ctx.beginPath()
        ctx.strokeStyle = '#D6D6D6'
        ctx.moveTo(406, 1026)
        ctx.lineTo(422, 1008)
        ctx.stroke()
        ctx.closePath()
        ctx.beginPath()
        ctx.moveTo(406, 1026)
        ctx.lineTo(422, 1044)
        ctx.stroke()
        ctx.closePath()
        ctx.beginPath()
        ctx.strokeStyle = '#505050'
        ctx.lineWidth = 2;
        let lineX1 = 530 - lineWidth/2,
            lineX2 = 530 + lineWidth/2
        ctx.moveTo(lineX1, 1040)
        ctx.lineTo(lineX2, 1040)
        ctx.stroke()
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/zc_share@3x.jpg'
    })
  },
  drawCashbackinfo3(ctx,canvas){
    let item = this.data.buyedItem
    let txt = '下单再返' + item.estimatePoint + '元'
    let x = 64,y = 1136, r = 12, w = 700, h = 80
    const that = this;
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        ctx.save()
        ctx.beginPath()
        // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
        // 这里是使用 fill 还是 stroke都可以，二选一即可
        ctx.setFillStyle = 'transparent'
        // ctx.setStrokeStyle('transparent')
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        // 右上角
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        // 左下角
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        ctx.fillStyle = "#FDF7F1";
        ctx.fill()
        ctx.closePath()
        // 剪切
        ctx.clip()
        ctx.restore();
        ctx.textAlign = 'center';
        ctx.fillStyle = "#FF5555";
        ctx.font = "32px PingFangSC-Medium";
        ctx.fillText(txt, 414, 1190);
        console.log('img loaded')
        ctx.drawImage(img, 380, 1100, 72, 52);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/red.png'
      
      
    })
  },
  // 绘制商品图
  drawItemPic3(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        var x = 134,y = 264, r = 8, w = 560, h = 560
        ctx.save()
        ctx.beginPath()
        // ctx.beginPath()
        // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
        // 这里是使用 fill 还是 stroke都可以，二选一即可
        ctx.setFillStyle = 'transparent'
        // ctx.setStrokeStyle('transparent')
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        // 右上角
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        // 左下角
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        // ctx.stroke()
        ctx.closePath()
        // 剪切
        ctx.clip()
        ctx.drawImage(img, 134, 264, 560, 560);
        ctx.restore();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.buyedItem.image
    })
  },
  // 绘制标签
  drawItemTag3(ctx,canvas){
    const that = this
    let item = this.data.buyedItem
    var goodCommentsRate = '100'
    if(item.goodCommentsRate > 0){
      goodCommentsRate = item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 292, 798, 244, 52);
        ctx.font = "26px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 454, 834);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 330, 834);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制头像
  drawAvatar3(ctx,canvas){
    const that = this
    let txt1 = app.globalData.userInfo.nickname + '分享给你一个超值商品',
        txt2 = '长按识别二维码进入京多多'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 46, x = 42, y = 1318
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Medium";
        }else{
          ctx.font = "26px NotoSans-Medium";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 148, 1358);
        if(!app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Light";
        }else{
          ctx.font = "lighter 26px NotoSans";
        }
        ctx.fillText(txt2, 148, 1394);
        ctx.closePath()
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = app.globalData.userInfo.avatar
    })
  },
  // 绘制二维码
  drawDcode3(ctx,canvas){
    const that = this
    if(app.globalData.userInfo.hasShop){
      fromOf = '&fO=fsk'
    }else{
      fromOf = '&fO=fod'
    }
    return new Promise(function (resolve, reject) {
      var scene = 'userId=' + app.globalData.userInfo.userId + '&sku=' + that.data.buyedItem.skuId + fromOf
      console.log(scene.length)
      common.post({
        url: '/wxa/qrcode/getUnlimitQrcode', 
        data: {
          scene: scene,
          // page: 'pages/itemdetail/itemdetail',
          page: 'pages/itemdetail/itemdetail',
          sessionId: app.globalData.sessionId,
          width: '236',
          auto_color: 'false',
          line_color: '{"r":"255","g":"85","b":"85"}',
          is_hyaline: 'false'
        }
      })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          let img = canvas.createImage();
          img.onload = (e) => {
            console.log('img loaded')
            ctx.beginPath()
            let r = 68, x = 652, y = 1296
            ctx.save()
            ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.clip()
            ctx.drawImage(img, x + 7, y + 7, 122, 122);
            ctx.restore()
            resolve()
          }
          img.onerror = (e) => {
            console.error('err:', e)
          }
          img.src = res.data.qrcodeLink
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
    })
  },
  // 生成图片
  drawCanvas5(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 828,
        height: 1472,
        destWidth:828,
        destHeight:1472,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrc:res.tempFilePath,
          })
          wx.hideLoading()
        }
      })
    })
  },
  drawCanvas6(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 500,
        height: 400,
        destWidth:500,
        destHeight:400,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrcSmall:res.tempFilePath,
            showshareBox: true,
            shareTxt: '超实惠的价格，不分享一下嘛'
          })
          wx.hideLoading()
        }
      })
    })
  },
  onPageScroll: function (e) {
    if(e.scrollTop >= this.data.mystoretabtop){
      if(!this.data.fixed){
        this.setData({
          fixed: true
        })
      }
    }else{
      if(this.data.fixed){
        this.setData({
          fixed: false
        })
      }
    }
  },
})
